<template>
    <el-form ref="editFormRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="新闻标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入新闻标题" />
      </el-form-item>
  
      <el-form-item label="作者" prop="username">
        <el-input v-model="formData.username" placeholder="请输入作者姓名" disabled />
      </el-form-item>
  
      <el-form-item label="新闻分类" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择分类">
          <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
          />
        </el-select>
      </el-form-item>
  
      <el-form-item label="内容摘要" prop="summary">
        <el-input
            v-model="formData.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入内容摘要"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>
  
      <el-form-item label="新闻内容" prop="content">
        <div class="editor-container">
          <QuillEditor
              ref="quillEditor"
              v-model:content="formData.content"
              contentType="html"
              :options="editorOptions"
              class="editor-content"
              @blur="onEditorBlur"
          />
        </div>
      </el-form-item>
  
      <el-form-item label="来源类型" prop="sourceType">
        <el-select v-model="formData.sourceType" placeholder="请选择来源类型">
          <el-option label="原创" :value="1" />
          <el-option label="转载" :value="2" />
          <el-option label="翻译" :value="3" />
        </el-select>
      </el-form-item>
  
      <el-form-item label="发布时间">
        <el-date-picker
            v-model="formData.publishTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
  
      <el-form-item label="状态">
        <el-radio-group v-model="formData.statusCode">
          <el-radio :label="1">草稿</el-radio>
          <el-radio :label="2">待审核</el-radio>
          <el-radio :label="3">已发布</el-radio>
          <el-radio :label="4">已封禁</el-radio>
          <el-radio :label="5">已删除</el-radio>
        </el-radio-group>
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancelEdit" >取消</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script>
  import { QuillEditor } from '@vueup/vue-quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import axios from '@/utils/request';
  import { ElMessage } from 'element-plus';
  
  export default {
    name: 'NewsEditDialog',
    components: { QuillEditor },
    props: {
      formData: {
        type: Object,
        default: () => ({
          contentId: null,
          title: '',
          username: '',
          categoryId: '',
          summary: '',
          content: '',
          sourceType: 1,
          publishTime: '',
          statusCode: 1,
          readCount: 0,
          commentCount: 0,
          likeCount: 0,
          shareCount: 0
        })
      }
    },
    data() {
      return {
        categoryOptions: [],
        editorOptions: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              ['link', 'image', 'video'],
              ['clean']
            ]
          },
          placeholder: '请输入新闻内容...',
          theme: 'snow'
        },
        rules: {
          title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
          categoryId: [{ required: true, message: '请选择新闻分类', trigger: 'change' }],
          summary: [{ required: true, message: '请输入内容摘要', trigger: 'blur' }],
          content: [{
            validator: (rule, value, callback) => {
              const strippedValue = value.replace(/(<([^>]+)>)/gi, '').trim();
              if (!strippedValue) {
                callback(new Error('请输入新闻内容'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }]
        }
      };
    },
    methods: {
      loadCategories() {
        axios.get('/contents/page', { params: { current: 1, size: 100 } })
          .then(response => {
            this.categoryOptions = response.data.data.categoriesList || [];
          })
          .catch(error => {
            console.error('获取分类列表失败:', error);
            ElMessage.error('获取分类列表失败');
          });
      },
      onEditorBlur() {
        this.$refs.editFormRef.validateField('content');
      },
      submitForm() {
        this.$refs.editFormRef.validate(valid => {
          if (valid) {
            axios.post('/contents/saveOrUpdate', this.formData)
              .then(response => {
                if (response.data.code === 200) {
                  ElMessage.success('保存成功');
                  this.$emit('submit-success');
                } else {
                  ElMessage.error(response.data.msg || '保存失败');
                }
              })
              .catch(error => {
                console.error('保存失败:', error);
                ElMessage.error('保存失败，请重试');
              });
          }
        });
      },
      cancelEdit() {
        this.$emit('update:modelValue', false);
      }
    },
    created() {
      this.loadCategories();
    }
  };
  </script>
  
  <style scoped>
  .editor-container {
    position: relative;
  }
  
  .editor-content {
    height: 400px;
    margin-bottom: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
  
  .editor-container :deep(.ql-editor) {
    word-wrap: break-word;
    word-break: break-all;
    overflow-wrap: anywhere;
  }
  
  :deep(.ql-toolbar) {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
  
  :deep(.ql-container) {
    height: 350px;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
  }
  </style>